//
//  TechViewController.swift
//  ReadHub
//
//  Created by 龙轶群 on 2017/8/1.
//  Copyright © 2017年 longyiqun. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
import DGElasticPullToRefresh
import FDTemplateLayoutCell
import AlamofireImage
import SwiftMoment
import MMCardView
import PKHUD
import SwiftWebVC
import Koloda
import pop
import Instructions



private let frameAnimationSpringBounciness: CGFloat = 9
private let frameAnimationSpringSpeed: CGFloat = 16
private let kolodaCountOfVisibleCards = 2
private let kolodaAlphaValueSemiTransparent: CGFloat = 0.1

class TechViewController: UIViewController {
	
    
    // 所有新闻集合
    var news: NSMutableArray = []
	
	var cardsViewCollection: NSMutableArray = []
	
	// 引导Controller
	var coachMarksController = CoachMarksController()

	let unlikeText = "左滑不感兴趣!"
	let likeText = "右划喜欢!"
	let introText = "我们会根据你的滑动来调整之后的推送内容, 喜欢? 不喜欢? 你说了算!"
	let nextButtonText = "OK"
	
    // 当前页最后一个话题publish date
    var lastTimeStamp: String = ""
    var firstTimeStamp: String = ""
    // 当前页最开始一个话题OrderID
    var firstOrder: Int = 0
    //用了记录当前是否允许加载新数据（正则加载的时候会将其设为false，放置重复加载）
    var loadMoreEnable = true
	
	// Main View
	@IBOutlet weak var kolodaView: CustomKolodaView!
	
	@IBOutlet weak var leftBtn: UIButton!
	@IBOutlet weak var rightBtn: UIButton!

    
    // 主流程
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 取数据(第一次,所以是false)
        getTopics(isMore: false)
		
		// 定义coachMarks
		self.coachMarksController.overlay.allowTap = true
		self.coachMarksController.dataSource = self
		//self.coachMarksController.overlay.color = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5)
		
		// 定义coachMarks的 跳过
		let skipView = CoachMarkSkipDefaultView()
		skipView.setTitle("跳过", for: .normal)
		skipView.setTitleColor(UIColor.white, for: .normal)
		skipView.setBackgroundImage(nil, for: .normal)
		skipView.setBackgroundImage(nil, for: .highlighted)
		skipView.layer.cornerRadius = 0
		skipView.backgroundColor = Constants.redColor

		self.coachMarksController.skipView = skipView
		
    }
	
	override func viewDidAppear(_ animated: Bool) {
		super.viewDidAppear(animated)
		
		// 判断是否演示过
		let isFirst = UserDefaults.standard.string(forKey: "isFirstTour")
		
		// 如果是第一次, 则弹出引导页
		if isFirst == "1"{
			
		} else {
			self.coachMarksController.start(on: self)
		}
	}
	
	override func viewWillDisappear(_ animated: Bool) {
		super.viewWillDisappear(animated)
		
		self.coachMarksController.stop(immediately: true)
	}
	
	
	// 友盟分享?
    func umSocialParentView(_ defaultSuperView: UIView!) -> UIView! {
        return defaultSuperView
    }
	
    
    // 获取数据主方法
    internal func getTopics(isMore: Bool) -> () {
        
        var parameters: Parameters = [:]
        
        // 根据是不是获取更多来定义Parameters
        if (!isMore) {
            news = []
            parameters = ["pageSize": "20"]
        } else {
            
            // 如果是获取更多, 则标记为不能再获取新数据的状态
            loadMoreEnable = false
            parameters = ["lastCursor": self.lastTimeStamp, "pageSize": "10"]
        }
        
        // 解析News最新的
        Alamofire.request(Constants.techURL, parameters: parameters).responseJSON { response in
            if let JSONEntity = response.result.value {
                let jsonData = JSON(JSONEntity)
                
                // 判断节点数量大于0
                if (jsonData["data"].count > 0){
                    
                    // 循环取News填充数组
                    for (_, newsDataArray): (String, JSON) in jsonData["data"] {
                        
                        // 临时News对象
                        let tempNews = News()
                        
                        // Topic基本信息
                        tempNews.id = newsDataArray["id"].string
                        tempNews.title = newsDataArray["title"].string
                        tempNews.siteName = newsDataArray["siteName"].string
                        tempNews.publishDate = newsDataArray["publishDate"].string
                        tempNews.url = newsDataArray["url"].string
                        tempNews.summary = newsDataArray["summary"].string
                        tempNews.summaryAuto = newsDataArray["summaryAuto"].string
						tempNews.author = newsDataArray["authorName"].string
						
						if (tempNews.summaryAuto != "") {
                        	// 添加News到数组中
                        	self.news.add(tempNews)
						}			
                    }
                }
                
                // 数据获取完更新本地的一些tag
                if (self.news.count > 0) {
                    
                    self.lastTimeStamp = (self.news.lastObject as! News).publishDate!
                    self.firstTimeStamp = (self.news.firstObject as! News).publishDate!
                    
                    print ("最后1个元素的标准时间：" + self.lastTimeStamp)
                    print ("第1个元素的标准时间：" + self.firstTimeStamp)
                    
                    // 当前时间+8换成本地时间
                    let timeMoment = moment(self.lastTimeStamp)! + 8.hours
                    
                    // 获取时间戳
                    let timeInterval: TimeInterval = timeMoment.date.timeIntervalSince1970
                    let timeStamp = Int(timeInterval)
                    let timeStampString = String(timeStamp)
                    
                    print("时间戳：" + timeStampString + "000")
                    
                    // 换成毫秒的TimeStamp
                    self.lastTimeStamp = timeStampString + "000"
                    
                } else {
                    self.lastTimeStamp = ""
                    self.firstTimeStamp = ""
                }
            }
			
			//显示
			self.setupUI()
        }
    }
	
	func setupUI() -> () {
		
		kolodaView.alphaValueSemiTransparent = kolodaAlphaValueSemiTransparent
		kolodaView.countOfVisibleCards = kolodaCountOfVisibleCards
		kolodaView.delegate = self
		kolodaView.dataSource = self
		kolodaView.animator = BackgroundKolodaAnimator(koloda: kolodaView)
		
		self.modalTransitionStyle = UIModalTransitionStyle.flipHorizontal
		
		
	}
	
	//MARK: IBActions
	@IBAction func leftButtonTapped() {
		kolodaView?.swipe(.left)
	}
	
	@IBAction func rightButtonTapped() {
		kolodaView?.swipe(.right)
	}

}

//MARK: KolodaViewDelegate
extension TechViewController: KolodaViewDelegate {
	
	func kolodaDidRunOutOfCards(_ koloda: KolodaView) {

		getTopics(isMore: true)
		
	}
	
	func koloda(_ koloda: KolodaView, didSelectCardAt index: Int) {
		
		let pageURL = ((self.news[index]) as! News).url
		
		let webVC = SwiftModalWebVC(urlString: pageURL!, theme: .dark, dismissButtonStyle: .arrow)
		
		self.present(webVC, animated: true, completion: nil)
	}
	
	func kolodaShouldApplyAppearAnimation(_ koloda: KolodaView) -> Bool {
		return true
	}
	
	func kolodaShouldMoveBackgroundCard(_ koloda: KolodaView) -> Bool {
		return false
	}
	
	func kolodaShouldTransparentizeNextCard(_ koloda: KolodaView) -> Bool {
		return true
	}
	
	func koloda(kolodaBackgroundCardAnimation koloda: KolodaView) -> POPPropertyAnimation? {
		let animation = POPSpringAnimation(propertyNamed: kPOPViewFrame)
		animation?.springBounciness = frameAnimationSpringBounciness
		animation?.springSpeed = frameAnimationSpringSpeed
		return animation
	}
}

// MARK: KolodaViewDataSource
extension TechViewController: KolodaViewDataSource {
	
	func kolodaSpeedThatCardShouldDrag(_ koloda: KolodaView) -> DragSpeed {
		return .default
	}
	
	func kolodaNumberOfCards(_ koloda: KolodaView) -> Int {
		return news.count
	}
	
	func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {
		
		let techViewCard =  Bundle.main.loadNibNamed("TechCardView", owner: self, options: nil)?[0] as? TechCardView
		
		techViewCard?.frame = kolodaView.frame
		
		
		techViewCard?.summaryLable.text = (news[index] as! News).summaryAuto!
		
		techViewCard?.titleLable.text = (news[index] as! News).title!
	
		if ((news[index] as! News).author != nil) {
			techViewCard?.authorLable.text = (news[index] as! News).author!
		} else {
			techViewCard?.authorLable.text = ""
		}
		
		// 取时间
		var timeMoment = moment() - moment((news[index] as! News).publishDate!)!
		
		// 换成本地+8时区
		timeMoment = timeMoment - 8.hours
		// 设置时间
		if (timeMoment.seconds < 60) {
			techViewCard?.timeLable.text = "现在"
		} else if (timeMoment.minutes < 60) {
			techViewCard?.timeLable.text = String(Int(timeMoment.minutes)) + " 分钟前"
		} else if (timeMoment.hours < 24) {
			techViewCard?.timeLable.text = String(Int(timeMoment.hours)) + " 小时前"
		} else {
			techViewCard?.timeLable.text = String(Int(timeMoment.days)) + " 天前"
		}
		
		return techViewCard!
		
		//return UIImageView(image: UIImage(named: "\(index + 1)jpg"))
	}
	
	func koloda(_ koloda: KolodaView, viewForCardOverlayAt index: Int) -> OverlayView? {
		return Bundle.main.loadNibNamed("CustomOverlayView", owner: self, options: nil)?[0] as? OverlayView
	}

}

extension TechViewController: CoachMarksControllerDataSource {
	
	
	func numberOfCoachMarks(for coachMarksController: CoachMarksController) -> Int {
		return 3
	}
	
	func coachMarksController(_ coachMarksController: CoachMarksController, coachMarkAt index: Int) -> CoachMark {
		
		let flatCutoutPathMaker = { (frame: CGRect) -> UIBezierPath in
			return UIBezierPath(rect: frame)
		}
		
		var coachMark : CoachMark
		
		switch(index) {
			
		// unlike按钮
		case 1:
			
			//let fakeLeftBtn = UIView(frame: self.leftBtn.frame)
			
			//let tempFrame = CGRect(x: self.leftBtn.bounds.origin.x - 5, y: self.leftBtn.bounds.origin.y - 5, width: self.leftBtn.bounds.width + 10, height: self.leftBtn.bounds.height + 10)
			
			//fakeLeftBtn.frame = tempFrame
			
			coachMark = coachMarksController.helper.makeCoachMark(for: self.leftBtn)
			coachMark.arrowOrientation = .bottom
			
		// like按钮
		case 2:
			coachMark = coachMarksController.helper.makeCoachMark(for: self.rightBtn)
			coachMark.arrowOrientation = .bottom
		case 0:
			
			let fakeCenter = UIView()
			
			let tempFrame = CGRect(x: 30, y: self.view.bounds.height / 2 - 150, width: self.view.bounds.width - 60, height: 300)
			
			fakeCenter.frame = tempFrame
			
			coachMark = coachMarksController.helper.makeCoachMark(for: fakeCenter)
			coachMark.arrowOrientation = .top
			
		default:
			coachMark = coachMarksController.helper.makeCoachMark()
		}
		
		coachMark.gapBetweenCoachMarkAndCutoutPath = 6.0
		
		return coachMark
	}
	
	func coachMarksController(_ coachMarksController: CoachMarksController, coachMarkViewsAt index: Int, madeFrom coachMark: CoachMark) -> (bodyView: CoachMarkBodyView, arrowView: CoachMarkArrowView?) {
		
		
		let coachMarkBodyView = CustomCoachMarkBodyView()
		var coachMarkArrowView: CustomCoachMarkArrowView? = nil
		
		var width: CGFloat = 0.0
		
		
		switch(index) {
		
		case 1:
			coachMarkBodyView.hintLabel.text = self.unlikeText
			coachMarkBodyView.nextButton.setTitle(self.nextButtonText, for: UIControlState())
			
			if let unlikeButton = self.leftBtn {
				width = unlikeButton.bounds.width
			}
		case 2:
			coachMarkBodyView.hintLabel.text = self.likeText
			coachMarkBodyView.nextButton.setTitle(self.nextButtonText, for: UIControlState())
			
			if let likeButton = self.rightBtn {
				width = likeButton.bounds.width
			}
			
			// 更新本地信息
			UserDefaults.standard.set("1", forKey: "isFirstTour")
		case 0:
			coachMarkBodyView.hintLabel.text = self.introText
			coachMarkBodyView.nextButton.setTitle(self.nextButtonText, for: UIControlState())
			
			width = self.view.bounds.width - 60
			
		default: break
		}
		
		if let arrowOrientation = coachMark.arrowOrientation {
			coachMarkArrowView = CustomCoachMarkArrowView(orientation: arrowOrientation)
			
			// If the view is larger than 1/3 of the overlay width, we'll shrink a bit the width
			// of the arrow.
			let oneThirdOfWidth = self.view.window!.frame.size.width / 3
			let adjustedWidth = width >= oneThirdOfWidth ? width - 2 * coachMark.horizontalMargin : width
			
			coachMarkArrowView!.plate.addConstraint(NSLayoutConstraint(item: coachMarkArrowView!.plate, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: adjustedWidth))
		}
		
		return (bodyView: coachMarkBodyView, arrowView: coachMarkArrowView)
	}
	
	// 调整 跳过 View的位置
	func coachMarksController(_ coachMarksController: CoachMarksController, constraintsForSkipView skipView: UIView, inParent parentView: UIView) -> [NSLayoutConstraint]? {
		
		var constraints: [NSLayoutConstraint] = []
		var topMargin: CGFloat = 0.0
		
		if !UIApplication.shared.isStatusBarHidden {
			topMargin = UIApplication.shared.statusBarFrame.size.height
		}
		
		constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|[skipView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["skipView": skipView]))
		
		if UIApplication.shared.isStatusBarHidden {
			constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|[skipView]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["skipView": skipView]))
		} else {
			constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-topMargin-[skipView(==44)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: ["topMargin": topMargin],
																		  views: ["skipView": skipView]))
		}
		
		return constraints
	}
}

